package com.jlkj.web.shopnew.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.jlkj.web.shopnew.constant.Constant;
import com.jlkj.web.shopnew.constant.ConstantDateType;
import com.jlkj.web.shopnew.dto.DateDto;
import com.jlkj.web.shopnew.dto.StaticsCountDto;
import com.jlkj.web.shopnew.dto.StaticsDto;
import com.jlkj.web.shopnew.dto.UpdateFollowDto;
import com.jlkj.web.shopnew.enums.EnumLogType;
import com.jlkj.web.shopnew.pojo.User;
import com.jlkj.web.shopnew.pojo.mongo.CustomerBelongMongo;
import com.jlkj.web.shopnew.pojo.mongo.FollowMongo;
import com.jlkj.web.shopnew.pojo.mongo.LogMongo;
import com.jlkj.web.shopnew.request.*;
import com.jlkj.web.shopnew.service.ICompany;
import com.jlkj.web.shopnew.service.IOrders;
import com.jlkj.web.shopnew.service.IStaff;
import com.jlkj.web.shopnew.service.IUser;
import com.jlkj.web.shopnew.service.mongo.ICustomerBelongMongo;
import com.jlkj.web.shopnew.service.mongo.ILogMongo;
import com.jlkj.web.shopnew.util.DateUtil;
import com.mongodb.client.result.UpdateResult;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.text.MessageFormat;
import java.util.*;

@Service
public class LogMongoImpl implements ILogMongo {
    private static final Logger LOGGER = LogManager.getLogger(LogMongoImpl.class);

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private IStaff staffService;

    @Autowired
    private IOrders ordersService;

    @Autowired
    private ICompany companyService;

    @Autowired
    private IUser userService;

    @Autowired
    private ICustomerBelongMongo customerBelongMongo;


    @Override
    public Map<String, Object> getMyCustomerLog(GetMyCustomerLogResquest getMyCustomerLogResquest) {
        Criteria criteria = new Criteria().andOperator(
                Criteria.where("operationId").is(getMyCustomerLogResquest.getOperationId()));

        if (StringUtils.isNotBlank(getMyCustomerLogResquest.getDateType())
                && !ConstantDateType.ALL_DAY.equals(getMyCustomerLogResquest.getDateType())) {
            //累计不需要管
            Map<String, Date> startEndDay = DateUtil.getDateByType(
                    getMyCustomerLogResquest.getDateType(),
                    getMyCustomerLogResquest.getStartDay(),
                    getMyCustomerLogResquest.getEndDay()
            );

            criteria = criteria.and("updateTime").gte(
                    DateUtil.getFirstSecIntegralTime(startEndDay.get("startDay"))
            ).lte(
                    DateUtil.getLastSecIntegralTime(startEndDay.get("endDay"))
            );

        }
        if (3 != getMyCustomerLogResquest.getUserType()) {
            criteria = criteria.and("userType").is(getMyCustomerLogResquest.getUserType());
        }

        int page = getMyCustomerLogResquest.getPage() == 0 ? 10 : getMyCustomerLogResquest.getPage();
        int pageSize = getMyCustomerLogResquest.getPageSize() == 0 ? 10 : getMyCustomerLogResquest.getPageSize();

        PageRequest pageRequest = PageRequest.of(page - 1, pageSize);

        // 设置查询条件，分页
        Query query = Query.query(criteria)
                .with(Sort.by(Sort.Direction.DESC, "updateTime"))
                .with(pageRequest);
        Long count = mongoTemplate.count(query, LogMongo.class);//查询总记录数
        List<LogMongo> list = this.mongoTemplate.find(query, LogMongo.class);

        Map<String, Object> data = new HashMap<>();
        data.put("totalCount", count);
        data.put("list", list);
        return data;
    }

    @Override
    public UpdateResult updateFollow(UpdateFollowDto dto) {
        try {
            List<Integer> list = staffService.getStaffUids(dto.getBelongUid());
            Criteria criteria = new Criteria().andOperator(
                    Criteria.where("operationId").in(list),
                    Criteria.where("uid").is(dto.getUid()));
            Query query = Query.query(criteria);

            Update update = new Update();
            update.set("followNum", dto.getCount());
            update.set("lastFollowTime", dto.getLastFollowTime());
            return this.mongoTemplate.updateMulti(query, update, LogMongo.class);

        } catch (Exception e) {
            e.printStackTrace();
            LOGGER.error(e.getMessage());
        }
        return null;
    }

    @Override
    public void saveLogMongo(SaveLogRequest saveLogRequest) {



        int companyId = companyService.getCompanyId(saveLogRequest.getOperationId());
        if (companyId != -1){
            saveLogRequest.setCompanyId(companyId);
        }

        //查询userType
        GetUserInfoRequest getUserInfoRequest = new GetUserInfoRequest();
        getUserInfoRequest.setUid(saveLogRequest.getUid());
        getUserInfoRequest.setOperationId(saveLogRequest.getOperationId());
        int userType =  customerBelongMongo.getUserType(getUserInfoRequest);

        Criteria criteria = new Criteria().andOperator(
                Criteria.where("operationId").is(saveLogRequest.getOperationId()),
                Criteria.where("uid").is(saveLogRequest.getUid()),
                Criteria.where("logType").is(saveLogRequest.getLogType()));
        Query query = Query.query(criteria);
        query.with(new Sort(new Sort.Order(Sort.Direction.DESC,"id")));

        LogMongo bean = this.mongoTemplate.findOne(query, LogMongo.class);
        if (bean != null) {
            int type = bean.getLogType();
            if (EnumLogType.LOG_CHAT.getType() == type) {
                Date date = bean.getUpdateTime();
                Date dateNew = new Date();
                if (DateUtil.daysBetween(dateNew, date) <= 1) {
                    return;
                }
            }
            long num = bean.getNum();
            saveLogRequest.setNum(num + 1L);
        } else {
            saveLogRequest.setNum(1L);
        }


        if(EnumLogType.LOG_BUY.getType() == saveLogRequest.getLogType()){
            userType = 2;
        }

        //保存log日志
        User user = userService.selectByPrimaryKey(saveLogRequest.getUid());
        saveLogRequest.setCreateTime(DateUtil.getMongoDate());
        saveLogRequest.setUpdateTime(DateUtil.getMongoDate());
        saveLogRequest.setUserType(userType);

        saveLogRequest.setUserImg(user.getLogo());
        this.mongoTemplate.save(saveLogRequest, Constant.LOGMONGO);

        //保存customerBelong
        CustomerBelongMongo belongMongo = new CustomerBelongMongo();
        belongMongo.setPhone(user.getPhone());
        belongMongo.setUserName(user.getUsername());
        belongMongo.setUid(user.getId());
        belongMongo.setBelongUserName(saveLogRequest.getOperationName());
        belongMongo.setBelongUid(saveLogRequest.getOperationId());
        belongMongo.setUserType(userType);
        customerBelongMongo.saveCustomerBelong(belongMongo);

    }

    @Override
    public Map<String, Object> getListByLogType(GetListByLogTypeRequest getListByLogTypeRequest) {
        String type = getListByLogTypeRequest.getDateType();
        Criteria criteria = new Criteria().andOperator(
                Criteria.where("logType").is(getListByLogTypeRequest.getLogType())
        );
        Map<String, Date> date =
                DateUtil.getDateByType(type, getListByLogTypeRequest.getStartDay(), getListByLogTypeRequest.getEndDay());

        criteria.and("updateTime").gte(date.get("startDay")).lte(date.get("endDay"));
        int page = getListByLogTypeRequest.getPage() == 0 ? 1 : getListByLogTypeRequest.getPage();
        int pageSize = getListByLogTypeRequest.getPageSize() == 0 ? 10 : getListByLogTypeRequest.getPageSize();
        PageRequest pageRequest = PageRequest.of(page - 1, pageSize,
                Sort.by(Sort.Direction.DESC, "updateTime" ));

        // 设置查询条件，分页
        Query query = Query.query(criteria).with(pageRequest);
        Long count = mongoTemplate.count(query, LogMongo.class);//查询总记录数
        List<LogMongo> list = this.mongoTemplate.find(query, LogMongo.class);

        Map<String, Object> data = new HashMap<>();
        data.put("totalCount", count);
        data.put("list", list);
        return data;
    }


    @Override
    public Map<String, Object> getLogListByLogTypeAndUid(GetLogListByLogTypeAndUidRequest getLogListByLogTypeAndUidRequest) {
        String type = getLogListByLogTypeAndUidRequest.getDateType();
        Criteria criteria = new Criteria().andOperator(
                Criteria.where("logType").is(getLogListByLogTypeAndUidRequest.getLogType())
        );

        if (getLogListByLogTypeAndUidRequest.isBoss()) {
            List<Integer> list = staffService.getCompanyStaff(getLogListByLogTypeAndUidRequest.getUid());
            criteria.and("operationId").in(list);
        } else {
            criteria.and("operationId").is(getLogListByLogTypeAndUidRequest.getUid());
        }

        DateDto dateDto =
                DateUtil.getDayByType(type, getLogListByLogTypeAndUidRequest.getStartDay(),
                        getLogListByLogTypeAndUidRequest.getEndDay());

        criteria.and("updateTime").gte(dateDto.getStartDay()).lte(dateDto.getEndDay());
        int page = getLogListByLogTypeAndUidRequest.getPage() == 0 ? 1 : getLogListByLogTypeAndUidRequest.getPage();
        int pageSize = getLogListByLogTypeAndUidRequest.getPageSize() == 0 ? 10 : getLogListByLogTypeAndUidRequest.getPageSize();

        PageRequest pageRequest = PageRequest.of(page - 1, pageSize,
                Sort.by(Sort.Direction.DESC, "id"));

        // 设置查询条件，分页
        Query query = Query.query(criteria).with(pageRequest);
        Long count = mongoTemplate.count(query, LogMongo.class);//查询总记录数
        List<LogMongo> list = this.mongoTemplate.find(query, LogMongo.class);

        Map<String, Object> data = new HashMap<>();
        data.put("totalCount", count);
        data.put("list", list);
        return data;
    }

    @Override
    public Map<String, Object> getLogCountByLogTypeAndUid(GetLogCountByLogTypeAndUidRequest getLogCountByLogTypeAndUidRequest) {
        String type = getLogCountByLogTypeAndUidRequest.getDateType();
        Criteria criteria = new Criteria().andOperator(
                Criteria.where("logType").in(getLogCountByLogTypeAndUidRequest.getLogTypes())
        );

        if (getLogCountByLogTypeAndUidRequest.isBoss()) {
            List<Integer> list = staffService.getCompanyStaff(getLogCountByLogTypeAndUidRequest.getUid());
            criteria.and("operationId").in(list);
        } else {
            criteria.and("operationId").is(getLogCountByLogTypeAndUidRequest.getUid());
        }

        DateDto dateDto =
                DateUtil.getDayByType(type, getLogCountByLogTypeAndUidRequest.getStartDay(), getLogCountByLogTypeAndUidRequest.getEndDay());

        criteria.and("updateTime").gte(dateDto.getStartDay()).lte(dateDto.getEndDay());

        Aggregation agg = Aggregation.newAggregation(
                // 第一步：sql where 语句筛选符合条件的记录
                Aggregation.match(criteria),
                // 第二步：分组条件，设置分组字段
                Aggregation.group("logType").count().as("count")
                        .first("logType").as("logType"),
                Aggregation.project("count", "logType").andExclude("_id")
        );


        AggregationResults<JSONObject> results = mongoTemplate.aggregate(agg, Constant.LOGMONGO, JSONObject.class);
        List<JSONObject> mappedResults = results.getMappedResults();

        LOGGER.info(mappedResults);

        return null;


    }

    @Override
    public Map<String, Object> getLogListByUid(GetListByUidRequest getListByUidRequest) {

        List<Integer> listStaff = staffService.getStaffUids(getListByUidRequest.getUid());
        Criteria criteria = new Criteria().andOperator(
                Criteria.where("operationId").in(listStaff)
        );
        int page = getListByUidRequest.getPage() == 0 ? 1 : getListByUidRequest.getPage();
        int pageSize = getListByUidRequest.getPageSize() == 0 ? 10 : getListByUidRequest.getPageSize();
        PageRequest pageRequest = PageRequest.of(page - 1, pageSize,
                Sort.by(Sort.Direction.DESC, "updateTime"));
        // 设置查询条件，分页
        Query query = Query.query(criteria).with(pageRequest);
        Long count = mongoTemplate.count(query, LogMongo.class);//查询总记录数
        List<LogMongo> list = this.mongoTemplate.find(query, LogMongo.class);

        Map<String, Object> data = new HashMap<>();
        data.put("totalCount", count);
        data.put("list", list);
        return data;
    }

    //我的跟进所有统计
    @Override
    public Map<String, Object> getMyFollowStatics(GetMyFollowStatiscRequest getMyFollowStatiscRequest) {

        List<JSONObject> userTypeStaticsResult = new ArrayList<>();
        JSONObject getUserType0 = getUserType(0, getMyFollowStatiscRequest.getUid());
        JSONObject getUserType1 = getUserType(1, getMyFollowStatiscRequest.getUid());
        JSONObject getUserType2 = getUserType(2, getMyFollowStatiscRequest.getUid());
        userTypeStaticsResult.add(getUserType0);
        userTypeStaticsResult.add(getUserType1);
        userTypeStaticsResult.add(getUserType2);


        List<JSONObject> getFollowByUserTypeResult = getFollowByUserType(getMyFollowStatiscRequest);
        List<JSONObject> getChatStaticsResult = getChatStatics(getMyFollowStatiscRequest);
        List<JSONObject> getMyFollowCountResult = getMyFollowCount(getMyFollowStatiscRequest);

        Map<String, Object> data = new HashMap<>();
        data.put("userTypeStatics", userTypeStaticsResult);//潜在客户  意向客户  和 客户
        data.put("getFollowByUserTypeResult", getFollowByUserTypeResult);
        data.put("getChatStaticsResult", getChatStaticsResult);
        data.put("getMyFollowCountResult", getMyFollowCountResult);
        return data;
    }


    //统计潜在客户  意向客户  客户
    private JSONObject getUserType(int type, int uid) {
        Criteria criteria = new Criteria().andOperator(
                Criteria.where("operationId").is(uid),
                Criteria.where("updateTime").lte(new Date()),
                Criteria.where("updateTime").gte(DateUtil.rollDay(new Date(), -10))
        );
        criteria.and("userType").is(type);
        Aggregation agg = Aggregation.newAggregation(
                // 第一步：sql where 语句筛选符合条件的记录
                Aggregation.match(criteria),
                // 第二步：分组条件，设置分组字段
                Aggregation.group().count().as("num")
                        .first("userType").as("userType"),
                Aggregation.project("num", "userType").andExclude("_id")
        );
        AggregationResults<JSONObject> results = mongoTemplate.aggregate(agg, Constant.CUSTOMERBELONGMONGO, JSONObject.class);
        List<JSONObject> userTypeStaticsResult = results.getMappedResults();
        return (userTypeStaticsResult == null || userTypeStaticsResult.size() == 0) ?
                new JSONObject() :
                userTypeStaticsResult.get(0);
    }


    //统计跟进人数  意向客户跟进  潜在客户跟进
    private List<JSONObject> getFollowByUserType(GetMyFollowStatiscRequest getMyFollowStatiscRequest) {
        Criteria criteria = new Criteria().andOperator(
                Criteria.where("operationId").is(getMyFollowStatiscRequest.getUid()),
                Criteria.where("updateTime").lte(new Date()),
                Criteria.where("updateTime").gte(DateUtil.rollDay(new Date(), -10))
        );
        Aggregation agg = Aggregation.newAggregation(
                // 第一步：sql where 语句筛选符合条件的记录
                Aggregation.match(criteria),
                // 第二步：分组条件，设置分组字段
                Aggregation.group("userType", "belongUid").count().as("num")
                        .first("userType").as("userType"),
                Aggregation.project("num", "userType").andExclude("_id")

        );
        AggregationResults<JSONObject> results = mongoTemplate.aggregate(agg, Constant.FOLLOWMONGO, JSONObject.class);
        List<JSONObject> mappedResults = results.getMappedResults();
        return mappedResults;
    }

    //统计聊天人数
    public List<JSONObject> getChatStatics(GetMyFollowStatiscRequest getMyFollowStatiscRequest) {
        Criteria criteria = new Criteria().andOperator(
                Criteria.where("operationId").is(getMyFollowStatiscRequest.getUid()),
                Criteria.where("logType").is(EnumLogType.LOG_CHAT.getType()),
                Criteria.where("updateTime").lte(new Date()),
                Criteria.where("updateTime").gte(DateUtil.rollDay(new Date(), -10))
        );
        Aggregation agg = Aggregation.newAggregation(
                // 第一步：sql where 语句筛选符合条件的记录
                Aggregation.match(criteria),
                // 第二步：分组条件，设置分组字段
                Aggregation.group().count().as("num")
                        .first("userType").as("userType"),
                Aggregation.project("num", "userType").andExclude("_id")

        );
        AggregationResults<JSONObject> results = mongoTemplate.aggregate(agg, Constant.LOGMONGO, JSONObject.class);
        List<JSONObject> mappedResults = results.getMappedResults();
        return mappedResults;
    }


    //统计我的跟进数
    public List<JSONObject> getMyFollowCount(GetMyFollowStatiscRequest getMyFollowStatiscRequest) {
        Criteria criteria = new Criteria().andOperator(
                Criteria.where("belongUid").is(getMyFollowStatiscRequest.getUid()),
                Criteria.where("updateTime").lte(new Date()),
                Criteria.where("updateTime").gte(DateUtil.rollDay(new Date(), -10))
        );
        Aggregation agg = Aggregation.newAggregation(
                // 第一步：sql where 语句筛选符合条件的记录
                Aggregation.match(criteria),
                // 第二步：分组条件，设置分组字段
                Aggregation.group().count().as("num")
                        .first("userType").as("userType"),
                Aggregation.project("num", "userType").andExclude("_id")

        );
        AggregationResults<JSONObject> results = mongoTemplate.aggregate(agg, Constant.FOLLOWMONGO, JSONObject.class);
        List<JSONObject> mappedResults = results.getMappedResults();
        return mappedResults;
    }


    //统计所有
    @Override
    public Map<String, Object> getStatics(StatiscRequest statiscRequest) {
        DateDto dateDto = DateUtil.getDayByType(statiscRequest.getDateType(),
                statiscRequest.getStartDay(), statiscRequest.getEndDay());


        Map<String, Object> data = new HashMap<>();
        StaticsDto countDto = new StaticsDto();
        //统计潜在客户人数
        //统计新增潜在客户数
        int potentialUserCountResultNew = getUserTypeCountNew(statiscRequest,dateDto,0);
        int potentialUserAddCountResultNew = getUserTypeAddCountNew(statiscRequest, dateDto, 0);

        //int potentialUserCountResult = getUserTypeCount(statiscRequest, dateDto, "potentialTime");
//        int potentialUserAddCountResult = getUserTypeAddCount(statiscRequest, dateDto, "potentialTime");

        //统计意向客户人数
        int intentionalUserCountResultNew =  getUserTypeCountNew(statiscRequest,dateDto,1);
        int intentionalUserAddCountResultNew = getUserTypeAddCountNew(statiscRequest, dateDto, 1);

       // int intentionalUserCountResult = getUserTypeCount(statiscRequest, dateDto, "intentionalTime");
        //统计新增意向客户数
      //  int intentionalUserAddCountResult = getUserTypeAddCount(statiscRequest, dateDto, "intentionalTime");


        //统计客户人数
        int customerUserCountResultNew =  getUserTypeCountNew(statiscRequest,dateDto,2);
        int customerUserAddCountResultNew = getUserTypeAddCountNew(statiscRequest, dateDto, 2);

        //int customerUserCountResult = getUserTypeCount(statiscRequest, dateDto, "customerTime");
        //统计新增客户数
       // int customerUserAddCountResult = getUserTypeAddCount(statiscRequest, dateDto, "customerTime");

        //统计聊天人数
        int chatCountResult = getChatCount(statiscRequest, dateDto);
        int chatAddCountResult = getChatAddCount(statiscRequest, dateDto);


        //统计潜在客户跟进  意向客户跟进
        List<StaticsCountDto> getUserTypeFollowCountResult = getUserTypeFollowCount(statiscRequest, dateDto);
        int potentialUserFollowCountResult = 0;
        int intentionalUserFollowCountResult = 0;
        if (getUserTypeFollowCountResult == null || getUserTypeFollowCountResult.size() == 0) {
        } else {

            for (StaticsCountDto dto : getUserTypeFollowCountResult) {
                //0表示潜在客户
                if (dto.getStaticsType() == 0) {
                    potentialUserFollowCountResult = dto.getCount();
                }

                //1表示意向客户
                if (dto.getStaticsType() == 1) {
                    intentionalUserFollowCountResult = dto.getCount();
                }
            }
        }

        List<StaticsCountDto> getUserTypeFollowAddCountResult = getUserTypeFollowAddCount(statiscRequest, dateDto);

        int potentialUserFollowAddCountResult = 0;
        int intentionalUserFollowAddCountResult = 0;
        if (getUserTypeFollowAddCountResult == null || getUserTypeFollowAddCountResult.size() == 0) {
        } else {

            for (StaticsCountDto dto : getUserTypeFollowCountResult) {
                //0表示潜在客户
                if (dto.getStaticsType() == 0) {
                    potentialUserFollowAddCountResult = dto.getCount();
                }

                //1表示意向客户
                if (dto.getStaticsType() == 1) {
                    intentionalUserFollowAddCountResult = dto.getCount();
                }
            }
        }


        //统计咨询跟进数
        Integer followAfterChatCountResult = getFollowAfterChatCount(statiscRequest, dateDto);
        Integer followAfterChatAddCountResult = getFollowAfterChatAddCount(statiscRequest, dateDto);

        //统计订单数
        Integer orderCount = ordersService.getOrdersCount(statiscRequest,dateDto);
        Integer orderAddCount = ordersService.getOrdersAddCount(statiscRequest,dateDto);

        //统计商业总额
        BigDecimal realPriceCount = ordersService.getRealPriceCount(statiscRequest,dateDto);
        BigDecimal realPriceAddCount = ordersService.getRealPriceAddCount(statiscRequest,dateDto);


        countDto = StaticsDto.builder()
                //统计用户相关
                .potentialUserCountResult(potentialUserCountResultNew)
                .potentialUserAddCountResult(potentialUserAddCountResultNew)

                .intentionalUserCountResult(intentionalUserCountResultNew)
                .intentionalUserAddCountResult(intentionalUserAddCountResultNew)

                .customerUserCountResult(customerUserCountResultNew)
                .customerUserAddCountResult(customerUserAddCountResultNew)
                //统计咨询数
                .chatAddCountResult(chatAddCountResult)
                .chatCountResult(chatCountResult)

                //统计跟进数
                .potentialUserFollowCountResult(potentialUserFollowCountResult)
                .potentialUserFollowAddCountResult(potentialUserFollowAddCountResult)

                .intentionalUserFollowCountResult(intentionalUserFollowCountResult)
                .intentionalUserFollowAddCountResult(intentionalUserFollowAddCountResult)

                //统计咨询跟进数
                .followAfterChatCountResult(followAfterChatCountResult)
                .followAfterChatAddCountResult(followAfterChatAddCountResult)

                //统计订单数
                .orderAddCountResult(orderAddCount)
                .orderCountResult(orderCount)

                //统计商业额
                .amountCountResult(realPriceCount)
                .amountAddCountResult(realPriceAddCount)
                .build();

        data.put("count", countDto);
        return data;
    }

  /////////////////////////////////////统计chat/////////////////////////////////////////////////
    @Override
    public Integer getChatCount(StatiscRequest statiscRequest,DateDto dateDto) {
        Criteria criteria = new Criteria().andOperator(
                Criteria.where("logType").is(EnumLogType.LOG_CHAT.getType()));
        if (ConstantDateType.ALL_DAY.equals(statiscRequest.getDateType())) {
            criteria.and("updateTime").lte(dateDto.getEndDay());
        } else {
            criteria.and("updateTime").lte(dateDto.getEndDay()).gte(dateDto.getStartDay());
        }


        if (statiscRequest.isBoss()) {
            List<Integer> list = staffService.getCompanyStaff(statiscRequest.getUid());
            criteria.and("operationId").in(list);
        } else {
            criteria.and("operationId").is(statiscRequest.getUid());
        }

        long count = mongoTemplate.count(Query.query(criteria),LogMongo.class);

        return (int) count;

       /* Aggregation agg = Aggregation.newAggregation(
                // 第一步：sql where 语句筛选符合条件的记录
                Aggregation.match(criteria),
                // 第二步：分组条件，设置分组字段
                Aggregation.group().count().as("num"),
                Aggregation.project("num").andExclude("_id")

        );
        AggregationResults<Integer> results = mongoTemplate.aggregate(agg, Constant.LOGMONGO, Integer.class);
        List<Integer> mappedResults = results.getMappedResults();

        return (mappedResults == null || mappedResults.size() == 0) ? 0 : mappedResults.get(0);*/

    }

    //统计聊天新增
    //TODO 修改时间
    @Override
    public Integer getChatAddCount(StatiscRequest statiscRequest,DateDto dateDto) {

        Criteria criteria = new Criteria().andOperator(
                Criteria.where("logType").is(EnumLogType.LOG_CHAT.getType()),
                Criteria.where("updateTime").lte(dateDto.getEndAddDay()),
                Criteria.where("updateTime").gte(dateDto.getStartAddDay())
        );

        if (statiscRequest.isBoss()) {
            List<Integer> list = staffService.getCompanyStaff(statiscRequest.getUid());
            criteria.and("operationId").in(list);
        } else {
            criteria.and("operationId").is(statiscRequest.getUid());
        }

        long count = mongoTemplate.count(Query.query(criteria),LogMongo.class);

        return (int) count;

       /* Aggregation agg = Aggregation.newAggregation(
                // 第一步：sql where 语句筛选符合条件的记录
                Aggregation.match(criteria),
                // 第二步：分组条件，设置分组字段
                Aggregation.group().count().as("num"),
                Aggregation.project("num").andExclude("_id")

        );
        AggregationResults<Integer> results = mongoTemplate.aggregate(agg, Constant.LOGMONGO, Integer.class);
        List<Integer> mappedResults = results.getMappedResults();

        return (mappedResults == null || mappedResults.size() == 0) ? 0 : mappedResults.get(0);*/
    }

    ///////////////////////////////////////////chatEnd////////////////////////////////////////////////////
    public Integer getUserTypeAddCountNew(StatiscRequest statiscRequest, DateDto dateDto, int userType) {

        Criteria criteria = new Criteria();
        if (ConstantDateType.ALL_DAY.equals(statiscRequest.getDateType())) {
            criteria.and("updateTime").lte(dateDto.getEndDay());
        } else {
            criteria.and("updateTime").lte(dateDto.getEndAddDay()).gte(dateDto.getStartAddDay());
        }

        criteria.and("userType").is(userType);
        if (statiscRequest.isBoss()) {
            List<Integer> list = staffService.getCompanyStaff(statiscRequest.getUid());
            criteria.and("operationId").in(list);
        } else {
            criteria.and("operationId").is(statiscRequest.getUid());
        }

        Aggregation agg = Aggregation.newAggregation(
                // 第一步：sql where 语句筛选符合条件的记录
                Aggregation.match(criteria),
                // 第二步：分组条件，设置分组字段
                Aggregation.group("uid").count().as("num")
                        .first("userType").as("userType"),
                Aggregation.group().count().as("num"),
                Aggregation.project("num").andExclude("_id")
        );


        AggregationResults<LogMongo> results = mongoTemplate.aggregate(agg,Constant.LOGMONGO, LogMongo.class);
        List<LogMongo> mappedResults = results.getMappedResults();

        if(mappedResults != null && mappedResults.size() > 0){
            LogMongo logMongo = mappedResults.get(0);
            return (int) logMongo.getNum();
        }

        return 0;

        /*
        AggregationResults<Integer> results = mongoTemplate.aggregate(agg, Constant.CUSTOMERBELONGMONGO, Integer.class);
        List<Integer> mappedResults = results.getMappedResults();
        return (mappedResults == null || mappedResults.size() == 0) ? 0 : mappedResults.get(0);*/
    }

    @Override
    public Integer getUserTypeCountNew(StatiscRequest statiscRequest, DateDto dateDto, int userType) {
        Criteria criteria = new Criteria();
        if (ConstantDateType.ALL_DAY.equals(statiscRequest.getDateType())) {
            criteria.and("updateTime").lte(dateDto.getEndDay());
        } else {
            criteria.and("updateTime").lte(dateDto.getEndDay()).gte(dateDto.getStartDay());
        }

        criteria.and("userType").is(userType);
        if (statiscRequest.isBoss()) {
            List<Integer> list = staffService.getCompanyStaff(statiscRequest.getUid());
            criteria.and("operationId").in(list);
        } else {
            criteria.and("operationId").is(statiscRequest.getUid());
        }

        Aggregation agg = Aggregation.newAggregation(
                // 第一步：sql where 语句筛选符合条件的记录
                Aggregation.match(criteria),
                // 第二步：分组条件，设置分组字段
                Aggregation.group("uid").count().as("num")
                        .first("userType").as("userType"),
                Aggregation.group().count().as("num"),
                Aggregation.project("num").andExclude("_id")
        );

        AggregationResults<LogMongo> results = mongoTemplate.aggregate(agg,Constant.LOGMONGO, LogMongo.class);
        List<LogMongo> mappedResults = results.getMappedResults();

        if(mappedResults != null && mappedResults.size() > 0){
            LogMongo logMongo = mappedResults.get(0);
            return (int) logMongo.getNum();
        }

        return 0;

    }


    //统计潜在客户
    //TODO 修改时间
    @Override
    public Integer getUserTypeCount(StatiscRequest statiscRequest, DateDto dateDto, String timeType) {
        Criteria criteria = new Criteria();
        if (ConstantDateType.ALL_DAY.equals(statiscRequest.getDateType())) {
            criteria.and(timeType).lte(dateDto.getEndDay());
        } else {
            criteria.and(timeType).lte(dateDto.getEndDay()).gte(dateDto.getStartDay());
        }

        if (statiscRequest.isBoss()) {
            List<Integer> list = staffService.getCompanyStaff(statiscRequest.getUid());
            criteria.and("belongUid").in(list);
        } else {
            criteria.and("belongUid").is(statiscRequest.getUid());
        }


        long count = mongoTemplate.count(Query.query(criteria),CustomerBelongMongo.class);

        return (int) count;

       /* Aggregation agg = Aggregation.newAggregation(
                // 第一步：sql where 语句筛选符合条件的记录
                Aggregation.match(criteria),
                // 第二步：分组条件，设置分组字段
                Aggregation.group().count().as("num"),
                Aggregation.project("num").andExclude("_id")
        );
        AggregationResults<Integer> results = mongoTemplate.aggregate(agg,
                Constant.CUSTOMERBELONGMONGO, Integer.class);
        List<Integer> mappedResults = results.getMappedResults();
        return (mappedResults == null || mappedResults.size() == 0) ? 0 : mappedResults.get(0);*/

    }

    //统计各个类型的用户增量
    //TODO 修改时间
    @Override
    public Integer getUserTypeAddCount(StatiscRequest statiscRequest, DateDto dateDto, String timeType) {

        Criteria criteria = new Criteria();

        criteria.andOperator(
                Criteria.where(timeType).lte(dateDto.getEndAddDay()),
                Criteria.where(timeType).gte(dateDto.getStartAddDay())
        );


        if (statiscRequest.isBoss()) {
            List<Integer> list = staffService.getCompanyStaff(statiscRequest.getUid());
            criteria.and("belongUid").in(list);
        } else {
            criteria.and("belongUid").is(statiscRequest.getUid());
        }

       /* Aggregation agg = Aggregation.newAggregation(
                // 第一步：sql where 语句筛选符合条件的记录
                Aggregation.match(criteria),
                // 第二步：分组条件，设置分组字段
                Aggregation.group().count().as("num"),
                Aggregation.project("num").andExclude("_id")
        );*/

        long count = mongoTemplate.count(Query.query(criteria),CustomerBelongMongo.class);

        return (int) count;

        /*
        AggregationResults<Integer> results = mongoTemplate.aggregate(agg, Constant.CUSTOMERBELONGMONGO, Integer.class);
        List<Integer> mappedResults = results.getMappedResults();
        return (mappedResults == null || mappedResults.size() == 0) ? 0 : mappedResults.get(0);*/
    }


    /////////////////////////////////////////客户统计///////////////////////////////////////////

    ///////////////////////////////////统计客户跟进//////////////////////////////////////////
    //TODO 修改时间
    @Override
    public List<StaticsCountDto> getUserTypeFollowCount(StatiscRequest statiscRequest, DateDto dateDto) {
        Criteria criteria = new Criteria().andOperator(
                Criteria.where("userType").in(Lists.newArrayList(0, 1))
        );
        if (ConstantDateType.ALL_DAY.equals(statiscRequest.getDateType())) {
            criteria.and("updateTime").lte(dateDto.getEndDay());
        } else {
            criteria.and("updateTime").lte(dateDto.getEndDay()).gte(dateDto.getStartDay());
        }


        if (statiscRequest.isBoss()) {
            List<Integer> list = staffService.getCompanyStaff(statiscRequest.getUid());
            criteria.and("belongUid").in(list);
        } else {
            criteria.and("belongUid").is(statiscRequest.getUid());
        }

        Aggregation agg = Aggregation.newAggregation(
                // 第一步：sql where 语句筛选符合条件的记录
                Aggregation.match(criteria),
                // 第二步：分组条件，设置分组字段
                Aggregation.group("userType","uid").count().as("count").first("userType").as("staticsType"),
                Aggregation.project("count", "staticsType").andExclude("_id")
        );
        AggregationResults<StaticsCountDto> results = mongoTemplate.aggregate(agg, Constant.FOLLOWMONGO, StaticsCountDto.class);
        List<StaticsCountDto> mappedResults = results.getMappedResults();
        return mappedResults;
    }



    @Override
    public List<StaticsCountDto> getUserTypeFollowAddCount(StatiscRequest statiscRequest, DateDto dateDto) {

        Criteria criteria = new Criteria().andOperator(
                Criteria.where("userType").in(Lists.newArrayList(0, 1)),
                Criteria.where("updateTime").lte(dateDto.getEndDay()),
                Criteria.where("updateTime").gte(dateDto.getStartDay())
        );

        if (statiscRequest.isBoss()) {
            List<Integer> list = staffService.getCompanyStaff(statiscRequest.getUid());
            criteria.and("belongUid").in(list);
        } else {
            criteria.and("belongUid").is(statiscRequest.getUid());
        }

        Aggregation agg = Aggregation.newAggregation(
                // 第一步：sql where 语句筛选符合条件的记录
                Aggregation.match(criteria),
                // 第二步：分组条件，设置分组字段
                Aggregation.group("userType","uid").count().as("count").first("userType").as("staticsType"),
                Aggregation.project("count", "staticsType").andExclude("_id")
        );
        AggregationResults<StaticsCountDto> results = mongoTemplate.aggregate(agg, Constant.FOLLOWMONGO, StaticsCountDto.class);
        List<StaticsCountDto> mappedResults = results.getMappedResults();
        return mappedResults;
    }

    ///////////////////////////////////统计客户跟进//////////////////////////////////////////



    //////////////////////////////////////////咨询跟进////////////////////////////////////////////////////
    //统计跟进表
    //TODO 修改时间
    @Override
    public Integer getFollowAfterChatCount(StatiscRequest statiscRequest, DateDto dateDto) {
        Criteria criteria = new Criteria().andOperator(
                Criteria.where("isAfterChat").is(1)
        );
        if (ConstantDateType.ALL_DAY.equals(statiscRequest.getDateType())) {
            criteria.and("updateTime").lte(dateDto.getEndDay());
        } else {
            criteria.and("updateTime").lte(dateDto.getEndDay()).gte(dateDto.getStartDay());

        }

        if (statiscRequest.isBoss()) {
            List<Integer> list = staffService.getCompanyStaff(statiscRequest.getUid());
            criteria.and("belongUid").in(list);
        } else {
            criteria.and("belongUid").is(statiscRequest.getUid());
        }

        long count = mongoTemplate.count(Query.query(criteria),FollowMongo.class);

        return (int) count;

       /* Aggregation agg = Aggregation.newAggregation(
                // 第一步：sql where 语句筛选符合条件的记录
                Aggregation.match(criteria),
                // 第二步：分组条件，设置分组字段
                Aggregation.group().count().as("num"),
                Aggregation.project("num").andExclude("_id")
        );
        AggregationResults<Integer> results = mongoTemplate.aggregate(agg, Constant.FOLLOWMONGO, Integer.class);
        List<Integer> mappedResults = results.getMappedResults();
        return (mappedResults == null || mappedResults.size() == 0) ? 0 : mappedResults.get(0);*/
    }

    //统计跟进新增
    //TODO 修改时间
    @Override
    public Integer getFollowAfterChatAddCount(StatiscRequest statiscRequest, DateDto dateDto) {
        Criteria criteria = new Criteria().andOperator(
                Criteria.where("isAfterChat").is(1),
                Criteria.where("updateTime").lte(dateDto.getEndDay()),
                Criteria.where("updateTime").gte(dateDto.getStartDay())
        );

        if (statiscRequest.isBoss()) {
            List<Integer> list = staffService.getCompanyStaff(statiscRequest.getUid());
            criteria.and("belongUid").in(list);
        } else {
            criteria.and("belongUid").is(statiscRequest.getUid());
        }

        long count = mongoTemplate.count(Query.query(criteria),FollowMongo.class);

        return (int) count;

       /* Aggregation agg = Aggregation.newAggregation(
                // 第一步：sql where 语句筛选符合条件的记录
                Aggregation.match(criteria),
                // 第二步：分组条件，设置分组字段
                Aggregation.group().count().as("num"),
                Aggregation.project("num").andExclude("_id")
        );
        AggregationResults<Integer> results = mongoTemplate.aggregate(agg, Constant.FOLLOWMONGO, Integer.class);
        List<Integer> mappedResults = results.getMappedResults();
        return (mappedResults == null || mappedResults.size() == 0) ? 0 : mappedResults.get(0);*/
    }


    //////////////////////////////////////////咨询跟进////////////////////////////////////////////////////


    //统计不同行为的记录数(时间+行为类型分组统计)
    @Override
    public Map<String, Object> getLogListCountByLogType(GetLogCountByLogTypeAndUidRequest getLogCountByLogTypeAndUidRequest) {
        DateDto dateDto = DateUtil.getDayByType(getLogCountByLogTypeAndUidRequest.getDateType(),
                getLogCountByLogTypeAndUidRequest.getStartDay(), getLogCountByLogTypeAndUidRequest.getEndDay());

        List<Integer> logTypeList=Lists.newArrayList();
        int[] logTypes = getLogCountByLogTypeAndUidRequest.getLogTypes();
        if(logTypes.length!=0){
            for(int log:logTypes){
                logTypeList.add(log);
            }
        }

        Criteria criteria = new Criteria().andOperator(
                Criteria.where("logType").in(logTypeList)
        );

        if (getLogCountByLogTypeAndUidRequest.isBoss()) {
            List<Integer> list = staffService.getCompanyStaff(getLogCountByLogTypeAndUidRequest.getUid());
            criteria.and("operationId").in(list);
        } else {//只统计员工自己
            criteria.and("operationId").is(getLogCountByLogTypeAndUidRequest.getUid());
        }
        criteria.and("updateTime").lte(dateDto.getEndDay()).gte(dateDto.getStartDay());

        Aggregation agg = Aggregation.newAggregation(
                // 第一步：sql where 语句筛选符合条件的记录
                Aggregation.match(criteria),
                // 第二步：分组条件，设置分组字段
                Aggregation.group("logType").count().as("num")
                        .first("logType").as("logType"),
                Aggregation.project("num","logType").andExclude("_id")
        );


        AggregationResults<LogMongo> results = mongoTemplate.aggregate(agg, Constant.LOGMONGO, LogMongo.class);
        List<LogMongo> mappedResults = results.getMappedResults();
        Map<String, Object> map=new HashMap<String,Object>();
        map.put("list",mappedResults);
        return map;
    }

    @Override
    public Map<String, Object> getLogListByCustomer(GetLogListByCustomerRequest getLogListByCustomerRequest) {
        int page = getLogListByCustomerRequest.getPage() == 0 ? 1 : getLogListByCustomerRequest.getPage();
        int pageSize = getLogListByCustomerRequest.getPageSize() == 0 ? 10 : getLogListByCustomerRequest.getPageSize();
        int totalCount=0;

        Map<String, Object> map=new HashMap<String,Object>();

        Criteria criteria = new Criteria();
        if(getLogListByCustomerRequest.isBoss()){
            List<Integer> list = staffService.getCompanyStaff(getLogListByCustomerRequest.getOperationId());
            criteria.where("operationId").in(list);
        }else{
            criteria.where("operationId").is(getLogListByCustomerRequest.getOperationId());//and 会自动去除第一个多余的
        }
        Aggregation agg = Aggregation.newAggregation(
                // 第一步：sql where 语句筛选符合条件的记录
                Aggregation.match(criteria),
                Aggregation.sort(Sort.Direction.DESC,"updateTime"),
                Aggregation.group("uid","logType").max("updateTime").as("updateTime")
                        .first("userName").as("userName")
                        .first("operationName").as("operationName")
                        .first("num").as("num"),
                Aggregation.sort(Sort.Direction.DESC,"updateTime")
        );
        totalCount=mongoTemplate.aggregate(agg, Constant.LOGMONGO, LogMongo.class).getMappedResults().size();
        map.put("totalCount",totalCount);

        agg = Aggregation.newAggregation(
                Aggregation.match(criteria),
                Aggregation.sort(Sort.Direction.DESC,"updateTime"),
                Aggregation.group("uid","logType").max("updateTime").as("updateTime")
                        .first("userName").as("userName")
                        .first("operationName").as("operationName")
                        .first("num").as("num"),
                Aggregation.sort(Sort.Direction.DESC,"updateTime"),
                Aggregation.skip((page-1)*pageSize),
                Aggregation.limit(pageSize)
        );

        AggregationResults<LogMongo> results = mongoTemplate.aggregate(agg, Constant.LOGMONGO, LogMongo.class);
        List<LogMongo> mappedResults = results.getMappedResults();
        map.put("list",mappedResults);
        return map;
    }
}
